package org.gesplan.controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.gesplan.entity.Location;
import org.gesplan.entity.LocationGroup;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.exceptions.PreexistingEntityException;


/**
 *
 * @author Roger
 */
public class LocationJpaController {

    public LocationJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Location location) throws PreexistingEntityException, Exception {

        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            LocationGroup locationGroupId = location.getLocationGroupId();
            if (locationGroupId != null) {
                locationGroupId = em.getReference(locationGroupId.getClass(), locationGroupId.getId());
                location.setLocationGroupId(locationGroupId);
            }
            em.persist(location);
            if (locationGroupId != null) {
                locationGroupId.getLocationCollection().add(location);
                em.merge(locationGroupId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findLocation(location.getId()) != null) {
                throw new PreexistingEntityException("Location " + location + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void edit(Location location) throws NonexistentEntityException, Exception {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Location persistentLocation = em.find(Location.class, location.getId());
            LocationGroup locationGroupIdOld = persistentLocation.getLocationGroupId();
            LocationGroup locationGroupIdNew = location.getLocationGroupId();
            if (locationGroupIdNew != null) {
                locationGroupIdNew = em.getReference(locationGroupIdNew.getClass(), locationGroupIdNew.getId());
                location.setLocationGroupId(locationGroupIdNew);
            }
            location = em.merge(location);
            if (locationGroupIdOld != null && !locationGroupIdOld.equals(locationGroupIdNew)) {
                locationGroupIdOld.getLocationCollection().remove(location);
                locationGroupIdOld = em.merge(locationGroupIdOld);
            }
            if (locationGroupIdNew != null && !locationGroupIdNew.equals(locationGroupIdOld)) {
                locationGroupIdNew.getLocationCollection().add(location);
                em.merge(locationGroupIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = location.getId();
                if (findLocation(id) == null) {
                    throw new NonexistentEntityException("The location with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void destroy(String id) throws NonexistentEntityException {
    	
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Location location;
            try {
                location = em.getReference(Location.class, id);
                location.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The location with id " + id + " no longer exists.", enfe);
            }
            LocationGroup locationGroupId = location.getLocationGroupId();
            if (locationGroupId != null) {
                locationGroupId.getLocationCollection().remove(location);
                em.merge(locationGroupId);
            }
            em.remove(location);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public List<Location> findLocationEntities() {
        return findLocationEntities(true, -1, -1);
    }

    public List<Location> findLocationEntities(int maxResults, int firstResult) {
        return findLocationEntities(false, maxResults, firstResult);
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private List<Location> findLocationEntities(boolean all, int maxResults, int firstResult) {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Location.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
        
    }

    
    public Location findLocation(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Location.class, id);
        } finally {
            em.close();
        }
    }
    

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int getLocationCount() {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Location> rt = cq.from(Location.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
        
    }
    
    
}